﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B303Langf.Parser.CodeGenerator
{
   public class Instruction
   {
      public Instruction()
      {
         OpCode = 0;
         Register = 0;
         Length = 0;
         Displacement = 0;
      }

      // C# has no type synonyms, so the following representations are
      // assumed:
      //
      //  type
      //    OpCode = 0..15;  {4 bits unsigned}
      //    Length = 0..255;  {8 bits unsigned}
      //    Operand = -32767..+32767;  {16 bits signed}

      // Represents TAM instructions.
      public int OpCode
      {
         get;
         set;
      }

      public int Register
      {
         get;
         set;
      }

      public int Length
      {
         get;
         set;
      }

      public int Displacement
      {
         get;
         set;
      }

      public void Write( BinaryWriter output )
      {
         output.Write( ChangeEndianess( OpCode ) );
         output.Write( ChangeEndianess( Register ) );
         output.Write( ChangeEndianess( Length ) );
         output.Write( ChangeEndianess( Displacement ) );
      }

      public byte[] ChangeEndianess( int value )
      {
         int index = 0;
         int bytes = 4;
         byte[] buffer = new byte[ bytes ];
         int endOffset = index + bytes - 1;
         for( int i = 0 ; i < bytes ; i++ )
         {
            buffer[ endOffset - i ] = unchecked( (byte) ( value & 0xFF ) );
            value = value >> 8;
         }
         return buffer;
      }
   }
}